package com.leyou.user.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.item.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;



@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private BCryptPasswordEncoder cryptPasswordEncoder;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;




    //根据用户名和密码查询
    @Override
    public UserDTO queryUserByUsernamePassword(String username, String password) {

       //根据用户名查询用户信息是否存在
        User user = this.query().eq("username", username).one();
        //存在则效验效验
        if (user == null) {
            throw new LyException("用户不存在", 400);
        }

        //明文密码进行加密与数据库中密文密码进行效验
        //String encode = cryptPasswordEncoder.encode(password);
        //matches方法首先会根据算法，推测密文的盐值，拿着盐值，对密码的文明加密，
        //加密后匹配两个密码信息
        if (!cryptPasswordEncoder.matches(password,user.getPassword())) {
            throw new LyException("密码错误", 400);
        }

        return new UserDTO(user);
    }


    //判断信息是否存在,数据的类型，1：用户名，2：手机号
    @Override
    public Boolean isExistsInfo(String date, Integer type) {
        if (type != 1 && type != 2) {
            throw new LyException("请求参数有误", 400 );
        }

        boolean b = this.query()
                .eq(type == 1, "username", date)
                .eq(type == 2, "phone", date)
                .count()==1;

        return b;
    }







    //用户注册
    @Override
    @Transactional
    public void loginUser(String username, String password, String phone, String code) {
        //效验验证码
        String cacheCode = redisTemplate.opsForValue().get("lySMS" + phone);
        System.out.println("redis-cacheCode = " + cacheCode);
        System.out.println("我收到的code = " + code);
        if (StringUtils.isEmpty(code)||!StringUtils.equals(code, cacheCode)) {
            throw new LyException("验证码错误", 400);
        }

        //密码加密
        String encode = cryptPasswordEncoder.encode(password);
        User user = new User();
        user.setUsername(username);
        user.setPhone(phone);
        user.setPassword(encode);

        this.save(user);
    }



    //发送短信验证码
    @Override
    public void codeSms(String phone) {
        //验证手机号码
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException("手机号码格式错误", 400);
        }

        //随机生成6位数验证码
        String code = RandomStringUtils.randomNumeric(6);

        //存储到redis并设置缓存时间
        redisTemplate.opsForValue().set("lySMS" + phone, code, 5, TimeUnit.MINUTES);

        //mq发送
        Map<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        String routingKey = "codeSms";
        amqpTemplate.convertAndSend("lySMS",routingKey,msg);
    }

//
//    @Autowired
//    private JwtUtils jwtUtils;
//
//    /**
//     * 获取用户名用于前端页面回显
//     * jwt --> token
//     * @param request
//     * @return
//     */
//    @Override
//    public UserDetail queryUsername(HttpServletRequest request ) {
//
//        String token = null;
//        Cookie[] cookies = request.getCookies();
//        for (Cookie cookie : cookies) {
//            if ("KY_TOKEN".equals(cookie.getName())) {
//                token = cookie.getValue();
//            }
//        }
//        //调用自定义工具类过去jwk
//        //String jwt = CookieUtils.getCookieValue(request, "KY_TOKEN");
//        // 验证并解析
//        Payload payload = jwtUtils.parseJwt(token);
//        // 获取用户
//        UserDetail userDetails = payload.getUserDetail();
//
//        return userDetails;
//    }

}
